package com.cjw.service.impl.livesquare;

import com.cjw.config.annotation.AutoFieldSuffer;
import com.cjw.enums.AutoFieldType;
import com.cjw.enums.FileType;
import com.cjw.mapper.database.MinioFileMapper;
import com.cjw.mapper.livesquare.LiveSharingMapper;
import com.cjw.mapper.livesquare.LiveUserMapper;
import com.cjw.mapper.livesquare.LivingMinioMapper;
import com.cjw.pojo.dto.database.UserDTO;
import com.cjw.pojo.dto.livesquare.LiveSharingDTO;
import com.cjw.pojo.query.livesquare.QueryAllDTO;
import com.cjw.pojo.entity.database.MinioFile;
import com.cjw.pojo.entity.livesquare.LiveSharing;
import com.cjw.pojo.entity.livesquare.LiveUser;
import com.cjw.pojo.entity.livesquare.LivingMinio;
import com.cjw.pojo.query.livesquare.AddLiveSharingCommand;
import com.cjw.pojo.query.livesquare.AddLoveCollectionQuery;
import com.cjw.pojo.query.livesquare.UpdateLivingShare;
import com.cjw.service.database.MinioService;
import com.cjw.service.livesquare.CommentService;
import com.cjw.service.livesquare.LiveSharingService;
import com.cjw.util.BaseContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * @create_time: 2021.11.15
 * @author : cjw
 * @descripe: 生活分享Service
 */
@Service("liveSharingService")
public class LiveSharingServiceImpl implements LiveSharingService {

    @Autowired
    private LiveSharingMapper liveSharingMapper;

    @Autowired
    private LiveUserMapper liveUserMapper;

    @Autowired
    private MinioService minioService;

    @Autowired
    private MinioFileMapper minioFileMapper;

    @Autowired
    private LivingMinioMapper livingMinioMapper;

    @Autowired
    private CommentService commentService;

    @Override
    public List<LiveSharingDTO> queryAllLiveDTO(Integer page, Integer size, String message) {
        QueryAllDTO queryAllDTO = new QueryAllDTO();
        queryAllDTO.setBegin(page*size);
        queryAllDTO.setSize(size);
        queryAllDTO.setMessage(message);
        queryAllDTO.setPower(0);
        List<LiveSharingDTO> liveSharingDTOS = liveSharingMapper.queryAllLiveDTO(queryAllDTO);
        UserDTO user = (UserDTO) BaseContextHolder.get("user");
        for (LiveSharingDTO liveSharingDTO : liveSharingDTOS) {
            LiveUser liveUser = new LiveUser();
            liveUser.setLiveId(liveSharingDTO.getId());
            liveUser.setUserId(user.getId());
            if (liveSharingDTO.getContext() == null)
                liveSharingDTO.setContext("");
            // 判断这个生活分享是否已经被用户操作了
            userIsDo(liveUserMapper.select(liveUser), liveSharingDTO);
            // 获取评论数
            liveSharingDTO.setCommentNum(commentService.getCommentNum(liveSharingDTO.getId(), 0));
        }
        return liveSharingDTOS;
    }

    // 判断这个生活分享是否已经被用户操作了
    private void userIsDo(List<LiveUser> select , LiveSharingDTO liveSharingDTO) {
        if (select.size() == 0) {
            liveSharingDTO.setLove(false);
            liveSharingDTO.setCollection(false);
        } else if (select.size() == 2) {
            liveSharingDTO.setLove(true);
            liveSharingDTO.setCollection(true);
        } else {
            if (select.get(0).getType() == 1) {
                liveSharingDTO.setLove(true);
                liveSharingDTO.setCollection(false);
            } else {
                liveSharingDTO.setLove(false);
                liveSharingDTO.setCollection(true);
            }
        }
    }

    @Override
    @AutoFieldSuffer(AutoFieldType.ADD)
    @Transactional(rollbackFor = Exception.class)
    public Boolean addCollection(Long id, Integer type) {
        AddLoveCollectionQuery addLoveCollectionQuery = new AddLoveCollectionQuery();
        UserDTO user = (UserDTO) BaseContextHolder.get("user");
        // 如果这个操作已存在，就删除（即取消点赞/收藏）,否则即添加
        LiveUser liveUser = new LiveUser();
        liveUser.setUserId(user.getId());
        liveUser.setLiveId(id);
        liveUser.setType(type);
        if (liveUserMapper.selectOne(liveUser) != null) {
            liveUserMapper.delete(liveUser);
            addLoveCollectionQuery.setNum(-1);
        } else {
            liveUser.setAddTime(new Date());
            liveUser.setUpdateTime(new Date());
            liveUserMapper.insert(liveUser);
            addLoveCollectionQuery.setNum(1);
        }

        addLoveCollectionQuery.setId(id);
        addLoveCollectionQuery.setType(type);
        if (type == 1)
            addLoveCollectionQuery.setCount(liveSharingMapper.selectByPrimaryKey(id).getLoveNum());
        else if (type == 2)
            addLoveCollectionQuery.setCount(liveSharingMapper.selectByPrimaryKey(id).getCollectionNum());
        return liveSharingMapper.addLoveCollection(addLoveCollectionQuery) == 1;
    }

    @Override
    public Long getNumLoveCollection(Long id, Integer type) {
        LiveSharing liveSharing1 = liveSharingMapper.selectByPrimaryKey(id);
        return type==1 ? liveSharing1.getLoveNum() : liveSharing1.getCollectionNum();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addShare(AddLiveSharingCommand command) {
        UserDTO user = (UserDTO) BaseContextHolder.get("user");
        LiveSharing liveSharing = new LiveSharing();
        liveSharing.setAddTime(new Date());
        liveSharing.setUpdateTime(new Date());
        liveSharing.setContext(command.getContext());
        liveSharing.setTopImage(command.getTopImage());
        liveSharing.setUserId(user.getId());
        liveSharing.setLoveNum(0L);
        liveSharing.setCollectionNum(0L);
        liveSharing.setPower(0);
        return liveSharingMapper.insertUseGeneratedKeys(liveSharing)==1?
                liveSharing.getId() : -1;
    }

    @Override
    public String getContextById(Long id) {
        return liveSharingMapper.selectByPrimaryKey(id).getContext();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String upImage(MultipartFile file) {
        return minioService.MinIOUpload(file, FileType.IMAGE.getCode());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveShare(UpdateLivingShare updateLivingShare) {
        UserDTO user = (UserDTO) BaseContextHolder.get("user");
        LiveSharing liveSharing = new LiveSharing();
        liveSharing.setId(updateLivingShare.getId());
        if (liveSharingMapper.selectByPrimaryKey(liveSharing).getUserId() != user.getId())
            return false;
        String context = updateLivingShare.getContext();
        if (context != null && !context.trim().equals(""))
            context = context.replaceAll("<img", "<img style=\"width: 70%\"");

        // 判断头图片
        LivingMinio livingMinio = new LivingMinio();
        livingMinio.setLiveId(updateLivingShare.getId());
        List<LivingMinio> select = livingMinioMapper.select(livingMinio);
        int min = Integer.MAX_VALUE;
        if (select.size() != 0) {
            for (LivingMinio livingMinio1 : select) {
                MinioFile minioFile1 = minioFileMapper.selectByPrimaryKey(livingMinio1.getMinioId());
                int i = context.indexOf(minioFile1.getUrl());
                if (i == -1) {
                    livingMinioMapper.deleteByPrimaryKey(livingMinio1.getId());
                } else {
                    if (min > i) {
                        min = i;
                        liveSharing.setTopImage(minioFile1.getUrl());
                    }

                }
            }
        }

        liveSharing.setId(updateLivingShare.getId());
        liveSharing.setUpdateTime(new Date());
        liveSharing.setContext(context);
        return liveSharingMapper.updateByPrimaryKeySelective(liveSharing)==1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean closeShare(UpdateLivingShare updateLivingShare) {
        UserDTO user = (UserDTO) BaseContextHolder.get("user");
        if (liveSharingMapper.selectByPrimaryKey(updateLivingShare.getId()).getUserId() != user.getId())
            return false;
        if (updateLivingShare.getContext() == null || updateLivingShare.getContext().equals("")) {
            liveSharingMapper.deleteByPrimaryKey(updateLivingShare.getId());
            return false;
        } else
            return saveShare(updateLivingShare);
    }

    @Override
    public Boolean updateLivingMinio(Long id, String imageUrl) {
        MinioFile minioFile = new MinioFile();
        minioFile.setUrl(imageUrl);
        LivingMinio livingMinio = new LivingMinio();
        livingMinio.setLiveId(id);
        livingMinio.setMinioId(minioFileMapper.selectOne(minioFile).getId());
        return livingMinioMapper.insert(livingMinio) == 1;
    }
}
